<template>
  <div class="shorten-form">
    <el-form :model="form" @submit.prevent="handleSubmit">
      <el-form-item>
        <el-input
          v-model="form.url"
          placeholder="请输入长链接"
          :prefix-icon="Link"
          clearable
        >
          <template #append>
            <el-button type="primary" @click="handleSubmit" :loading="loading">
              生成短链
            </el-button>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-date-picker
          v-model="form.expiresAt"
          type="datetime"
          placeholder="选择过期时间（可选）"
          :min-time="minTime"
        />
      </el-form-item>
    </el-form>

    <div v-if="shortUrl" class="result">
      <el-alert
        :title="shortUrl"
        type="success"
        :closable="false"
      >
        <template #default>
          <div class="result-actions">
            <el-button type="text" @click="copyUrl">
              复制链接
            </el-button>
            <el-button type="text" @click="openUrl">
              访问链接
            </el-button>
            <el-button type="text" @click="showQRCode">
              二维码
            </el-button>
          </div>
        </template>
      </el-alert>
    </div>

    <el-dialog v-model="qrDialogVisible" title="短链接二维码" width="300px" align-center>
      <div class="qr-code" ref="qrCodeRef"></div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, nextTick } from 'vue'
import { Link } from '@element-plus/icons-vue'
import { useShortenerStore } from '../store/shortener'
import { ElMessage } from 'element-plus'
import QRCode from 'qrcode'

const store = useShortenerStore()
const loading = ref(false)
const shortUrl = ref('')
const qrDialogVisible = ref(false)
const qrCodeRef = ref(null)

const minTime = computed(() => {
  return new Date()
})

const form = ref({
  url: '',
  expiresAt: null
})

const handleSubmit = async () => {
  if (!form.value.url) {
    ElMessage.warning('请输入链接')
    return
  }

  loading.value = true
  try {
    const result = await store.createShortUrl(form.value.url, form.value.expiresAt)
    shortUrl.value = `http://localhost:8000/${result.short_code}`
    ElMessage.success('短链接生成成功')
  } catch (error) {
    ElMessage.error(error.message || '生成失败')
  } finally {
    loading.value = false
  }
}

const copyUrl = async () => {
  try {
    await navigator.clipboard.writeText(shortUrl.value)
    ElMessage.success('复制成功')
  } catch (error) {
    ElMessage.error('复制失败')
  }
}

const openUrl = () => {
  window.open(shortUrl.value)
}

const showQRCode = async () => {
  qrDialogVisible.value = true
  await nextTick()
  try {
    // 清空之前的内容
    if (qrCodeRef.value) {
      qrCodeRef.value.innerHTML = ''
    }
    // 生成新的二维码
    const canvas = await QRCode.toCanvas(shortUrl.value, {
      width: 200,
      margin: 2
    })
    qrCodeRef.value.appendChild(canvas)
  } catch (error) {
    console.error('QR Code error:', error)
    ElMessage.error('二维码生成失败')
  }
}
</script>

<style scoped>
.shorten-form {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
}

.result {
  margin-top: 20px;
}

.result-actions {
  margin-top: 10px;
  display: flex;
  gap: 20px;
}

.qr-code {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
}
</style> 